package com.itany.shop.tran.impl;

import com.itany.shop.exception.ServiceException;
import com.itany.shop.tran.TransactionManager;
import com.itany.shop.util.JDBCUtil;

import java.sql.SQLException;

/**
 * @author 石小俊
 * @date 2023年07月05日 16:00
 */
public class TransactionManagerImpl implements TransactionManager {
    @Override
    public void begin() {
        try {
            JDBCUtil.getConnection().setAutoCommit(false);
        } catch (SQLException e) {
            throw new ServiceException("事务开启失败");
        }
    }

    @Override
    public void commit() {
        try {
            // 只有当前事务属于手动提交,才需要提交
            if(!JDBCUtil.getConnection().getAutoCommit()){
                JDBCUtil.getConnection().commit();
            }
        } catch (SQLException e) {
            throw new ServiceException("事务提交失败");
        } finally {
            // 事务结束之后释放资源
            JDBCUtil.close();
        }
    }

    @Override
    public void rollback() {
        try {
            // 只有当前事务属于手动提交,才需要回滚
            if(!JDBCUtil.getConnection().getAutoCommit()){
                JDBCUtil.getConnection().rollback();
            }
        } catch (SQLException e) {
            throw new ServiceException("事务提交失败");
        } finally {
            // 事务结束之后释放资源
            JDBCUtil.close();
        }
    }
}
